package org.lex.awt;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

import org.lex.utils.text.DateTimeUtilities;


public class SystemClipboard {
	private static final Clipboard systemClipboard;
	private static final ClipboardOwner owner;
	static {
		systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
		owner = new SimpleClipboardOwner();
	}

	static class SimpleClipboardOwner implements ClipboardOwner {
		public void lostOwnership(Clipboard clipboard, Transferable contents) {
			System.out.println(DateTimeUtilities.formatDateTime(System.currentTimeMillis()) + " : " + systemClipboard.getName()
					+ " Clipboard Contents Changed");
		}
	}

	private SystemClipboard() {
	}

	/**
	 * Place a String on the clipboard, and make this class the owner of the
	 * Clipboard's contents.
	 */
	public static void setClipboardContents(String text) {
		StringSelection stringSelection = new StringSelection(text);
		systemClipboard.setContents(stringSelection, owner);
	}

	/**
	 * Get the String residing on the clipboard.
	 * 
	 * @return any text found on the Clipboard; if none found, return an empty
	 *         String.
	 */
	public static String getClipboardContents() {
		String result = "";
		// odd: the Object param of getContents is not currently used
		Transferable contents = systemClipboard.getContents(null);
		boolean hasTransferableText = (contents != null) && contents.isDataFlavorSupported(DataFlavor.stringFlavor);
		if (hasTransferableText) {
			try {
				result = (String) contents.getTransferData(DataFlavor.stringFlavor);
			} catch (UnsupportedFlavorException e) {
				// highly unlikely since we are using a standard DataFlavor
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}
}
